﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CustomUIControls;
using System.Drawing;
using System.Text;
using System.IO;
using Lib.CommonForm;
using System.Data;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace AUI
{
    static class Program
    {
        internal static frmMain m_frmMain;
        internal static System.Windows.Forms.MenuStrip m_menuMain;
        internal static System.Windows.Forms.ToolStrip m_toolbarMain;
        


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            //if (AlreadyRunning())
            //    return;


            if (CheckIfAlreadyRunning())
                return;


            Globals.Application_SetCultureInfo(System.Threading.Thread.CurrentThread);

            FormGlobals.CreateTaskbarNotifier();

            Control.CheckForIllegalCrossThreadCalls = false;

            ToolStripManager.Renderer = new Office2007Renderer();

            FormGlobals.isRemoteWCF = true;

            Application.Run(new frmMain());
        }
  

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            try
            {
                FormGlobals.Message_Error(e.Exception);
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Error(ex);
            }
        }

        #region SW_RESTORE RETURN MainWindowHandle

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);


        static bool AlreadyRunning()
        {

            /*
            const int SW_HIDE = 0;
            const int SW_SHOWNORMAL = 1;
            const int SW_SHOWMINIMIZED = 2;
            const int SW_SHOWMAXIMIZED = 3;
            const int SW_SHOWNOACTIVATE = 4;
            const int SW_RESTORE = 9;
            const int SW_SHOWDEFAULT = 10;
            */
            const int swRestore = 9;

            var me = Process.GetCurrentProcess();
            var arrProcesses = Process.GetProcessesByName(me.ProcessName);

            if (arrProcesses.Length > 1)
            {
                for (var i = 0; i < arrProcesses.Length; i++)
                {
                    if (arrProcesses[i].Id != me.Id)
                    {
                        // get the window handle
                        IntPtr hWnd = arrProcesses[i].MainWindowHandle;

                        // if iconic, we need to restore the window
                        if (IsIconic(hWnd))
                        {
                            ShowWindowAsync(hWnd, swRestore);
                        }

                        // bring it to the foreground
                        SetForegroundWindow(hWnd);
                        break;
                    }
                }
                return true;
            }

            return false;
        }

        /// <summary>
        /// Check if another instance is running and give focus to it if it is
        /// </summary>
        /// <returns>true if another was found</returns>
        public static bool CheckIfAlreadyRunning()
        {
            string RegistryPath = @"Software\IAS";
            var reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryPath);
            if (reg != null)
            {
                try
                {
                    var processId = (int)reg.GetValue("ProcessId");
                    var otherProcess = System.Diagnostics.Process.GetProcessById(processId);
                    if (otherProcess.Id != Process.GetCurrentProcess().Id)
                        if (otherProcess.MainWindowHandle != IntPtr.Zero)
                        {
                            // need our own window to be in foreground so that we can give it to the other instance
                            try { SetForegroundWindow(otherProcess.MainWindowHandle); }
                            catch { }
                            //f.Close();
                            reg.Close();
                            return true;
                        }
                }
                catch { }
                reg.Close();
            }

            // register that we are running
            try
            {
                reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryPath, true);
                if (reg == null)
                    reg = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RegistryPath);
                reg.SetValue("ProcessId", Process.GetCurrentProcess().Id, Microsoft.Win32.RegistryValueKind.DWord);
                reg.Close();
            }
            catch { }
            return false;
        }

        #endregion
    }
}
